package com.littlebee.storysuper.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.littlebee.storysuper.R;
import com.littlebee.storysuper.adapter.CircleEnglistAdapter;
import com.littlebee.storysuper.adapter.CircleStoryAdapter;
import com.littlebee.storysuper.entry.EnglishCartoonsEntry;
import com.littlebee.storysuper.entry.EnglishEntry;
import com.littlebee.storysuper.entry.EnglistListEntry;
import com.littlebee.storysuper.entry.User;
import com.littlebee.storysuper.utils.DateUtils;
import com.littlebee.storysuper.utils.GsonUtils;
import com.littlebee.storysuper.utils.NetWorkUtils;
import com.littlebee.storysuper.utils.ToastUtil;
import com.littlebee.storysuper.utils.Utils;
import com.littlebee.storysuper.widget.AlwaysMarqueeTextView;
import com.littlebee.storysuper.widget.CircleImageView;
import com.littlebee.storysuper.widget.RoundAngleImageView;
import com.zss.library.activity.BaseActivity;
import com.zss.library.adapter.CommonAdapter;
import com.zss.library.adapter.ViewHolder;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.LogUtils;
import com.zss.library.widget.CommonProgressDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 英语
 */
public class EnglishActivity extends BaseActivity implements View.OnClickListener {
    private ListView gridView;
    //private CommonAdapter<EnglistListEntry> mAdapter;
    List<EnglishCartoonsEntry> names = new ArrayList<EnglishCartoonsEntry>();
    private CircleEnglistAdapter adapter;

    /**
     * 是否在播放
     */
    private boolean isPlaying;
    /**
     * 播放进度
     */
    private int currPost = 0;
    /**
     * 用于做延迟加载
     */
    private Handler handler = null;
    /**
     * 视频播放组件
     */
    private VideoView videoView;
    /**
     * 播放or暂停
     */
    private ImageView playPauseIv;
    /**
     * 播放进度
     */
    private TextView nowProgressTv;
    /**
     * 播放进度条
     */
    private SeekBar progressBar;
    /**
     * 总进度
     */
    private TextView totalLengthTv;
    /**
     * 全屏
     */
    private ImageView fullScreenIv;
    /**
     * 选集浮动层
     */
    private FrameLayout diversityFy;
    /**
     * 选集列表
     */
    private GridView diversityGv;
    /**
     * 播放以前的初始化图片
     */
    private ImageView videoInitIv;
    /**
     * 视频标题
     */
    private TextView videoTitleTv;
    /**
     * 分集评论数据
     */
    EnglishEntry diversityDatas = new EnglishEntry();
    private TextView total_tv;
    private ImageView show_to_player;
    View view;
    @Override
    public int getLayoutResId() {
        return R.layout.activity_english;
    }

    @Override
    public void initView() {
        super.initView();
        handler = new Handler();
        gridView = (ListView) findViewById(R.id.listview);
        view=getLayoutInflater(R.layout.activity_today_englist_top);
        videoInitIv = (ImageView)view. findViewById(R.id.init_video_iv);
        videoTitleTv = (TextView)view. findViewById(R.id.video_title_tv);

        videoView = (VideoView)view. findViewById(R.id.video_view);
        playPauseIv = (ImageView) view.findViewById(R.id.play_pause_iv);
        nowProgressTv = (TextView) view.findViewById(R.id.now_progress_tv);
        progressBar = (SeekBar) view.findViewById(R.id.progressBar);
        totalLengthTv = (TextView) view.findViewById(R.id.total_length_tv);
        playPauseIv.setOnClickListener(this);
        total_tv = (TextView) view.findViewById(R.id.total_tv);
        show_to_player=(ImageView)view.findViewById(R.id.show_to_player);

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        getInfo();
        getInfoTop();
//        mAdapter = new CommonAdapter<EnglistListEntry>(getActivity(), R.layout.layout_item_eng) {
//            @Override
//            protected void convert(ViewHolder viewHolder, final EnglistListEntry workerListEntry, int i) {
//                TextView name = viewHolder.findViewById(R.id.tv);
//                TextView name1 = viewHolder.findViewById(R.id.tv1);
//
//                RoundAngleImageView iv = viewHolder.findViewById(R.id.photo);
//                Glide.with(EnglishActivity.this).load(workerListEntry.getCartoonseriesminiphotourl()).error(R.mipmap.logo_img).into(iv);
//                name.setText(workerListEntry.getCatoonseriesname());
//                name1.setText(workerListEntry.getCartoonseriesstagecount()+"集  热度："+workerListEntry.getCartoonserieshotpoint());
//            }
//        };
//        gridView.setAdapter(mAdapter);
//        mAdapter.addAll(names);
//        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Intent intent = new Intent(EnglishActivity.this, EnglishInfoActivity.class);
//                intent.putExtra("info", names.get(position));
//                startActivity(intent);
//            }
//        });


    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.trans);

        toolbar.setTitle(getString(R.string.boby_eng_txt));


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_pause_iv:
                if (videoView != null && videoView.isPlaying()) {
                    playPauseIv.setImageResource(R.mipmap.ransfer_media_play);
                    currPost = videoView.getCurrentPosition();
                    videoView.pause();
                    isPlaying = false;
                } else {
                    playPauseIv.setImageResource(R.mipmap.ransfer_media_pause);
                    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            videoInitIv.setVisibility(View.GONE);
                            videoTitleTv.setVisibility(View.GONE);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    mHandler.sendEmptyMessageDelayed(1, 0);
                                }
                            }).start();
                        }
                    });
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mHandler.sendEmptyMessageDelayed(0, 0);
                        }
                    }).start();
                    play(diversityDatas.getEnglishdesvideoplayurl(), currPost);
                }
                break;
        }
    }

    /**
     * 获取列表
     */
    public void getInfo() {
        User user = Utils.getUserEntry();
        if (user != null) {
            HashMap<String, String> map = new HashMap<>();
            map.put("phoneId", user.getMobile());
            // TODO: 2017/8/15
            NetWorkUtils.post(EnglishActivity.this, "getenglishcartoons", map, true, new NetWorkUtils.IListener() {

                @Override
                public void onSuccess(String result, JSONObject resObj) {
                    String res = resObj.optString("response")/**.optString("storypages")*/;
                    names = GsonUtils.getListFromJSON(res, EnglishCartoonsEntry.class);
                    if (adapter == null) {
                        adapter = new CircleEnglistAdapter(names, EnglishActivity.this);
                        gridView.setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                    gridView.addHeaderView(view);
                }

                @Override
                public void onError(String result, String code, String msg) {
                    LogUtils.i("XHX", "XHXERROR:" + result);
                }
            });
        }
    }

    /**
     * 获取事例
     */
    public void getInfoTop() {
        User user = Utils.getUserEntry();
        if (user != null) {
            HashMap<String, String> map = new HashMap<>();
            map.put("phoneId", user.getMobile());
            // TODO: 2017/8/15
            NetWorkUtils.post(EnglishActivity.this, "getenglishdesinfo", map, true, new NetWorkUtils.IListener() {

                @Override
                public void onSuccess(String result, JSONObject resObj) {
                    String res = resObj.optString("response")/**.optString("storypages")*/;
                    diversityDatas = GsonUtils.getObjFromJSON(res, EnglishEntry.class);
                    // TODO: 2017/8/25
                    //diversityDatas.setEnglishdesvideoplayurl("http://47.92.37.125:9090/piecefile/1/babyvideo/2017-08-25-18611697983.mp4");
                    total_tv.setText(diversityDatas.getEnglishdestxt());

                    Glide.with(EnglishActivity.this).load(diversityDatas.getEnglishdesvideominiphoto()).error(R.color.module_video_bg).into(videoInitIv);
                    totalLengthTv.setText(DateUtils.getTimeString((Long.parseLong(diversityDatas.getEnglishdesvideoduration().trim())) * 1000));
                    show_to_player.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent=new Intent(EnglishActivity.this,PlayerInfoActivity.class);
                            intent.putExtra("url",diversityDatas.getEnglishdesvideoplayurl());
                            intent.putExtra("title",diversityDatas.getEnglishdestxt());
                            intent.putExtra("pic",diversityDatas.getEnglishdesvideominiphoto());
                            intent.putExtra("pos",0);
                            startActivity(intent);
                        }
                    });
                }

                @Override
                public void onError(String result, String code, String msg) {
                }
            });
        }
    }

    private void initPlayer(int diversityIndex, int currPost) {
        videoInitIv.setVisibility(View.GONE);
        videoTitleTv.setVisibility(View.GONE);

        playPauseIv.setImageResource(R.mipmap.ransfer_media_pause);

        videoTitleTv.setText(diversityDatas.getEnglishdestxt());
        play(diversityDatas.getEnglishdesvideoplayurl(), currPost);
    }

    private SeekBar.OnSeekBarChangeListener change = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 当进度条停止修改的时候触发
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (videoView != null && videoView.isPlaying()) {
                // 设置当前播放的位置
                videoView.seekTo(progress);
                //修改时间
            }
        }
    };

    /**
     * 播放咯
     *
     * @param path 地址
     * @param msec 播放进度
     */
    protected void play(String path, int msec) throws NullPointerException{
        //获取视频文件地址

        videoView.setVideoURI(Uri.parse(path));
        LogUtils.i("XHX", "初始化播放器了");
        //开始播放
        videoView.start();

        // 按照初始位置播放
        videoView.seekTo(msec);

        //修改时间
        // 开始线程，更新进度条的刻度
        new Thread() {
            @Override
            public void run() {
                try {
                    isPlaying = true;
                    while (isPlaying) {
                        // 如果正在播放，没0.5.毫秒更新一次进度条
                        int current = videoView.getCurrentPosition();
                        progressBar.setMax(videoView.getDuration());
                        progressBar.setProgress(current);
                        handler.post(runnableUi);
                        sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // 在播放完毕被回调 续播还是结束播放
//                if(diversityIndex<diversityDatas.size()-1){
//                    diversityIndex+=1;
//                    currPost=0;
//                    videoTitleTv.setText(diversityDatas.get(diversityIndex).getContent());
//                    play(diversityDatas.get(diversityIndex).getPath(),currPost);
//                }else{
                videoInitIv.setVisibility(View.VISIBLE);
                videoTitleTv.setVisibility(View.VISIBLE);
                //}
                ToastUtil.displayShortToast("播放结束");
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                //TODO  发生错误重新播放
                play(diversityDatas.getEnglishdesvideoplayurl(), 0);
                isPlaying = false;
                return false;
            }
        });
    }

    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面播放进度的文字标识
            if (videoView.getDuration() != -1) {
                totalLengthTv.setText(DateUtils.getTimeString(videoView.getDuration()));
            }
            nowProgressTv.setText(DateUtils.getTimeString(videoView.getCurrentPosition()));

        }

    };
    private static CommonProgressDialog dialog;

    public static void showProgressDialog(Context mContext, final String showStr) {
        if (mContext != null) {
            if (dialog == null) {
                dialog = new CommonProgressDialog(mContext);
                dialog.setTitle(showStr);
                dialog.setCancelable(true);
                dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
                        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                            dialog.dismiss();
                            dialog = null;
                        }
                        return false;
                    }
                });
                dialog.show();
            } else {
                if (!dialog.isShowing()) {
                    dialog.show();
                }
            }
        }
    }

    public static void dismissProgressDialog(Context mContext) {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    showProgressDialog(EnglishActivity.this,"正在缓冲……");
                    break;
                case 1:
                    dismissProgressDialog(EnglishActivity.this);
                    break;

            }
        }

    };
}
